﻿using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;

namespace Xwltz.Framework.Framework
{
    /// <summary>
    /// 描述：邮件发送
    /// ==声名对象==
    /// MailSmtp ms = new MailSmtp("smtp.qq.com","xxx","xx");
    /// ==可选参数==
    /// ms.SetCc("xxxx@qq.com");//抄送可以多个
    /// ms.SetBc("xxxx@qq.com");//暗送可以多个
    /// ms.SetIsHtml(true);//默认:true
    /// ms.SetEncoding(System.Text.Encoding.UTF8);//设置格式 默认utf-8
    /// ms.SetIsSsl(true);//是否ssl加密 默认为false
    /// ==调用函数==
    /// bool isSuccess = ms.Send("xx@qq.com", "test", "xxxxqq.com", "哈哈", "哈哈");
    /// ==获取返回值==
    /// var result = ms.Result
    /// </summary>
    public class MailSmtp
    {
        /// <summary>
        /// 设置邮件编码类型
        /// </summary>
        /// <param name="contentEncoding"></param>
        public void SetEncoding(Encoding contentEncoding)
        {
            Encoding = contentEncoding;

        }

        /// <summary>
        ///设置邮件正文是否为 Html 格式 
        /// </summary>
        /// <param name="isHtml"></param>
        public void SetIsHtml(bool isHtml)
        {
            IsHtml = isHtml;
        }

        /// <summary>
        /// 抄送
        /// </summary>
        /// <param name="cc"></param>
        public void SetCc(params string[] cc)
        {
            Cc = cc;
        }

        /// <summary>
        /// 暗送
        /// </summary>
        /// <param name="bc"></param>
        public void SetBc(params string[] bc)
        {
            Bcc = bc;
        }

        /// <summary>
        /// 是否ssl加密
        /// </summary>
        /// <param name="isSsl"></param>
        public void SetIsSsl(bool isSsl)
        {
            _smtp.EnableSsl = isSsl;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host"></param>
        /// <param name="username">邮件账号</param>
        /// <param name="password">密码</param>
        public MailSmtp(string host, string username, string password)
        {
            _smtp.Host = host;
            _smtp.Port = 0x19;
            _smtp.EnableSsl = false;
            IsHtml = true;
            Encoding = Encoding.UTF8;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                _smtp.UseDefaultCredentials = false;
            }
            else
            {
                _smtp.Credentials = new NetworkCredential(username, password);
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发件人邮件地址</param>
        /// <param name="sender">发件人显示名称</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件正文</param>
        /// <param name="file">附件地址数组</param>
        /// <returns>bool 是否成功 </returns>
        public bool Send(string from, string sender, string to, string subject, string body, params string[] file)
        {
            return Send(from, sender, new[] { to }, subject, body, file);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发件人邮件地址</param>
        /// <param name="sender">发件人显示名称</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件正文</param>
        /// <param name="file">附件地址数组</param>
        /// <returns>bool 是否成功 </returns>
        public bool Send(string from, string sender, string[] to, string subject, string body, params string[] file)
        {
            const string mailReg = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
            if (to == null)
            {
                throw new ArgumentNullException(nameof(to));
            }

            if (to.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
            {
                Result = "收件人地址不合法";
                return false;
            }
            if (Bcc != null && Bcc.Length > 0)
            {
                if (Bcc.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
                {
                    Result = "暗送人地址不合法";
                    return false;
                }
            }
            if (Cc != null && Cc.Length > 0)
            {
                if (Cc.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
                {
                    Result = "抄送人地址不合法";
                    return false;
                }
            }
            var message = new MailMessage();

            // 创建一个附件对象
            foreach (var r in file)
            {
                var objMailAttachment = new Attachment(r);
                message.Attachments.Add(objMailAttachment);
            }
            message.From = new MailAddress(from, sender);
            message.Subject = subject;
            message.SubjectEncoding = Encoding;
            message.Body = body;
            message.BodyEncoding = Encoding;
            message.IsBodyHtml = IsHtml;
            message.Priority = MailPriority.Normal;
            foreach (var str in to)
            {
                message.To.Add(str);
            }
            if (Bcc != null && Bcc.Length > 0)
            {
                foreach (var b in Bcc)
                {
                    message.Bcc.Add(b);
                }
            }
            if (Cc != null && Cc.Length > 0)
            {
                foreach (var c in Cc)
                {
                    message.CC.Add(c);
                }
            }

            try
            {
                _smtp.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }

            return false;
        }

        private readonly SmtpClient _smtp = new SmtpClient();
        private Encoding Encoding { get; set; }
        private bool IsHtml { get; set; }
        private string[] Cc { get; set; }
        private string[] Bcc { get; set; }
        /// <summary>
        /// 获取发送结果，成功则为空
        /// </summary>
        public string Result { get; private set; }
    }
}